package offer.diff;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;

/**
 * @author DengYuan2
 * @create 2021-03-09 19:21
 */
public class n_45 {
    public static void main(String[] args) {
        n_45 n = new n_45();
        int[] arr = {3, 32, 321};
        String res = n.PrintMinNumber(arr);
        System.out.println(res);
    }

    /**
     * 关键是如何比较两个数的大小
     * 在此基础上，我用得是冒泡排序
     *
     * @param numbers
     * @return
     */
    public String PrintMinNumber(int[] numbers) {
        boolean flag = false;
        for (int i = 0; i < numbers.length - 1; i++) {
            flag = false;
            for (int j = 0; j < numbers.length - 1 - i; j++) {
                if (compare(numbers[j], numbers[j + 1]) > 0) {
                    int tmp = numbers[j];
                    numbers[j] = numbers[j + 1];
                    numbers[j + 1] = tmp;
                    flag = true;
                }
            }
            if (!flag) {
                break;
            }
        }
        StringBuilder res = new StringBuilder();
        for (int i = 0; i < numbers.length; i++) {
            res.append(numbers[i]);
        }
        return res.toString();

    }

    /**
     * 比较的思路应该如下：
     * 比较的是 S1+S2 和 S2+S1 的大小，如果 S1+S2 < S2+S1
     *
     * @param a
     * @param b
     * @return
     */
    public int compare(int a, int b) {
        String s1 = "" + a;
        String s2 = "" + b;
        if ((s1 + s2).compareTo(s2 + s1) > 0) {
            return 1;
        }


        return -1;
    }

    public String PrintMinNumber2(int[] numbers) {
        ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < numbers.length; i++) {
            list.add(numbers[i]);
        }
        Comparator<Integer> comparator = new Comparator<Integer>() {
            @Override
            public int compare(Integer a, Integer b) {
                String s1 = a + "";
                String s2 = b + "";
                return (s1 + s2).compareTo(s2 + s1);
            }
        };
        Collections.sort(list,comparator);
        StringBuilder builder = new StringBuilder();
        for (int i:list){
            builder.append(i);
        }
        return builder.toString();

    }

}
